;
define(function() {

    function createModal(obj) {
        var settings = {
            id: null,
            title: null,
            defaultContainer: "body", //默认容器（元素class）
            container: null, //自定义容器（元素ID）	
            m_left: null,
            m_right: null,
            m_top: null,
            m_bottom: null,
            closeTip: true, //右上角的叉号
            width: null,
            height: null,
            header: true,
            hide: false, //true-隐藏/false-移除
            closed: function() { //右上角的叉号回调
            },
            callback: function() { //回调函数(点击头部回调)
            }
        };

        settings = $.extend(settings, obj);

        var id = "modal_";
        //传递id
        if (obj.id) {
            id += obj.id;
        }

        var modalDialog = $("<div id='" + id + "' style='position: absolute;margin:0;width:" + obj.width + "px;'></div>").addClass("modal-dialog");

        if (obj.m_left) {
            modalDialog.css({ 'left': obj.m_left });
        } else {
            //如果指定弹出框left
            if (obj.m_right) {
                modalDialog.css({ 'right': obj.m_right });
            } else {
                if (settings.container != null) {
                    modalDialog.css({ 'right': ($("#" + settings.container).width() - modalDialog.width()) / 2 + 'px' });
                } else {
                    modalDialog.css({ 'right': ($(settings.defaultContainer).width() - modalDialog.width()) / 2 + 'px' });
                }
            }
        }

        if (obj.m_top) {
            modalDialog.css({ 'top': obj.m_top });
        } else {
            if (obj.m_bottom) {
                modalDialog.css({ 'bottom': obj.m_bottom });
            } else {
                modalDialog.css({ 'bottom': '30px' });
            }
        }

        //弹出框内容
        var modalContent = $("<div></div>").addClass("modal-content");

        //弹出框头部
        var modalHeader = $("<div></div>").addClass("modal-header");

        //是否需要出现右上角的叉号
        if (obj.closeTip != false) {
            var close = $('<div class="close">×</div>')
            modalHeader.append(close);
            //关闭按钮的绑定事件
            close.on("click", function() {
                if ($.isFunction(obj.closed)) {
                    obj.closed(close.closest("div[id^='modal_']"));
                }
                //弹出框移除
                if (!obj.hide) {
                    $("div.modal-backdrop." + obj.id).remove();
                    modalDialog.remove();
                } else {
                    $("div.modal-backdrop." + obj.id).hide();
                    modalDialog.hide();
                }
            });
        }

        //弹出框标题

        var modalTitle = $("<div>").addClass("modal-title");
        if ("array" == $.type(obj.title)) {
            obj.title.forEach(function(t) {
                var $span = $('<span>').data("url", t.url).text(t.name);
                if (t.cls) {
                    $span.addClass(t.cls);
                }
                modalTitle.append($span);
            });
        } else {
            modalTitle.text(obj.title);
        }

        //弹出框主体
        var modalBody = $("<div style='height:" + obj.height + "px; overflow-y:auto'></div>").addClass("modal-body");

        modalHeader.append(modalTitle);
        if (settings.header)
        	modalContent.append(modalHeader)
        modalContent.append(modalBody);

        modalDialog.append(modalContent);

        if (settings.container != null) {
            $('#' + settings.container).append(modalDialog);
        } else {
            $(settings.defaultContainer).append(modalDialog);
        }

        //弹出框显示
        modalDialog.show();

        //单击弹出框的头部，确定点击处的位置
        $("#" + id).off().on('mousedown', '.modal-header', function(event) {
            $(this).css({ "cursor": "all-scroll" }); //点击鼠标切换图形
            event.stopPropagation();
            event.preventDefault();
            var isMove = true;
            var _this = $("#" + id);

            var m_x = Number(_this.css("left").split("px")[0]); //点击窗体时，left
            var m_y = Number(_this.css("top").split("px")[0]); //点击窗体时，top
            var abs_x = event.pageX; //点击窗体时，左边距
            var abs_y = event.pageY; //点击窗体时，上边距
            //单击住头部可进行拖拽，计算移动大小，以及移动范围限制
            $(document).unbind('mousemove').bind('mousemove', function(event) {
                if (isMove) {
                    //event.pageX,移动后的左边距;event.pageY,移动后的上边距
                    var ebs_x = m_x - (abs_x - event.pageX); //移动后的left
                    var ebs_y = m_y + (event.pageY - abs_y); //移动后的top

                    if (settings.container != null) {
                        var body_w = $("#" + settings.container).width();
                        var body_h = $("#" + settings.container).height();
                    } else {
                        var body_w = $(settings.defaultContainer).width();
                        var body_h = $(settings.defaultContainer).height();
                    }

                    var div_w = _this.width();
                    var div_h = _this.find(".modal-content").outerHeight();
                    //不可超出左右边框
                    if (ebs_x <= 0) {
                        ebs_x = 0;
                    } else if (ebs_x > body_w - div_w) {
                        ebs_x = body_w - div_w;
                    }
                    //不可超出上下边框
                    if (ebs_y <= 0) {
                        ebs_y = 0;
                    } else if (ebs_y > body_h - div_h) { //减去上下的蓝边高
                        ebs_y = body_h - div_h;
                    }

                    //重新设定弹出框的左边距，上边距
                    _this.css({ 'left': ebs_x, 'top': ebs_y });
                }
            }).mouseup(function() {
                isMove = false
                $(document).unbind('mousemove');
            }); //鼠标移除事件；单击事件结束事件。

            settings.callback();
        });
        $("#" + id + " .modal-title>span").off().on("click", function() {
            if (!$(this).hasClass("active")) {
                $(this).addClass("active").siblings().removeClass("active");
                $("#modal_" + obj.id + " .modal-body").load($(this).data("url"), obj.operateFuc, obj.loadSuccess);
            }
        });
    }

    var ModalBoxCreate = function(obj) {
            this.id = obj.id;
            if (obj.isBackdrop) backdrop(obj.id, obj.container);
            // 生成模态框
            createModal({
                id: obj.id,
                title: obj.title,
                container: obj.container,
                m_left: obj.m_left,
                m_right: obj.m_right,
                m_top: obj.m_top,
                m_bottom: obj.m_bottom,
                closeTip: obj.closeTip,
                width: obj.width,
                height: obj.height,
                hide: obj.hide,
                header: obj.header,
                closed: obj.closed,
                callback: obj.callback
            });
            if($.isFunction(obj.createSucc)){
                obj.createSucc($("#modal_" + obj.id));
    		}
            if (obj.url) {
                $("#modal_" + obj.id + " .modal-body").load(obj.url, obj.operateFuc, obj.loadSuccess);
            } else if (obj.html) {
                $("#modal_" + obj.id + " .modal-body").append(obj.html);
                if ($.isFunction(obj.showCall)) {
                    obj.showCall($("#modal_" + obj.id + " .modal-body"));
                }
            }
            if (obj.isTop) {
                var $modal = $("#modal_" + obj.id);
                $("div.modal-backdrop." + obj.id).css("z-index", parseInt($modal.css("z-index")) + 1);
                $modal.css("z-index", parseInt($modal.css("z-index")) + 2);
            }

        }
    //添加遮罩
    function backdrop(id, container) {
        $("div.modal-backdrop." + id).remove();
        var $backdrop = $('<div>').addClass('modal-backdrop ' + id);
        if (container) {
            $("#" + container).append($backdrop);
        } else {
            $("body").append($backdrop);
        }
    }

    //弹出窗口
    CafeJS.ModalBox = function(settings) {
        var modalBox = new ModalBoxCreate(settings);
        return modalBox;
    }

    // 关闭弹出框
    CafeJS.ModalBoxClose = function(id, callback) {
        if (callback) {
            callback($("#modal_" + id));
        }
        $("#modal_" + id).remove();
        $("div.modal-backdrop." + id).remove();
    };

    // 隐藏多个弹出框
    CafeJS.ModalBoxCloses = function(ids, callback) {
    	if (!ids || ids.length == 0) return;
    	ids.forEach(function(id){
    		$("#modal_" + id).remove();
            $("div.modal-backdrop." + id).remove();
            if (callback) {
                callback();
            }
    	})
    };

    // 隐藏弹出框
    CafeJS.ModalBoxHide = function(id, callback) {
        $("#modal_" + id).hide();
        $("div.modal-backdrop." + id).hide();
        if (callback) {
            callback();
        }
    };
    // 隐藏多个弹出框
    CafeJS.ModalBoxHides = function(ids, callback) {
    	if (!ids || ids.length == 0) return;
    	ids.forEach(function(id){
    		$("#modal_" + id).hide();
            $("div.modal-backdrop." + id).hide();
            if (callback) {
                callback();
            }
    	})
    };
    // 显示弹出框
    CafeJS.ModalBoxShow = function(id, callback) {
        $("#modal_" + id).show();
        $("div.modal-backdrop." + id).show();
        if (callback) {
            callback();
        }
    };

    // 是否存在
    CafeJS.ModalBoxExist = function(id, callback) {
        return $("#modal_" + id).length > 0;
    };

});